<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4">
        <el-input

            placeholder="请输入仓库名称"
            @input="getWarehouses"
        />
        <el-tree
            :data="data1"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :default-expand-all="true"
            :highlight-current="true"
            default-expand-all
            :loading="treeLoading"
            node-key="id"
        />
      </el-col>
      <el-col :span="20">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="仓库名称" prop="warehouseName">
            <el-input
                v-model="queryParams.warehouseName"
                placeholder="请输入仓库名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="物料名称" prop="materialName">
            <el-input
                v-model="queryParams.materialName"
                placeholder="请输入物料名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="预警值" prop="warningValue">
            <el-input
                v-model="queryParams.warningValue"
                placeholder="请输入预警值"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="库存状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择库存状态" clearable style="width: 193px">
              <el-option
                  v-for="dict in inventory_warning_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" prop="createdTime">
            <el-date-picker clearable
                            v-model="queryParams.createdTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择创建时间"
                            style="width: 193px">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="更新时间" prop="updatedTime">
            <el-date-picker clearable
                            v-model="queryParams.updatedTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择更新时间"
                            style="width: 193px">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['inventory:warning:add']"
                :disabled="warehouse.warehouseName === ''"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single && warehouse.warehouseName === ''"
                @click="handleUpdate"
                v-hasPermi="['inventory:warning:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple && warehouse.warehouseName === ''"
                @click="handleDelete"
                v-hasPermi="['inventory:warning:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="warning"
                plain
                icon="Download"
                @click="handleExport"
                v-hasPermi="['inventory:warning:export']"
                :disabled="warehouse.warehouseName === ''"
            >导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="warningList" @selection-change="handleSelectionChange" :row-class-name="getRowClass">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="id" align="center" prop="id"/>
          <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
          <el-table-column label="物料名称" align="center" prop="materialName"/>
          <el-table-column label="预警值" align="center" prop="warningValue"/>
          <el-table-column label="当前库存" align="center" prop="quantity"/>
          <el-table-column label="备注" align="center" prop="remarks"/>
          <el-table-column label="库存状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="inventory_warning_status" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" prop="updatedTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" :disabled="warehouse.warehouseName === ''"
                         v-hasPermi="['inventory:warning:edit']">修改
              </el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" :disabled="warehouse.warehouseName === ''"
                         v-hasPermi="['inventory:warning:remove']">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改库存预警对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
          <el-form ref="warningRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input v-model="form.warehouseName" readonly/>
            </el-form-item>
            <el-form-item label="物料名称" prop="materialName">
              <el-select v-model="form.materialId" placeholder="请输入物料名称">
                <el-option
                  v-for="item in materialsList"
                  :key="item.id"
                  :label="item.materialName"
                  :value="item.id || ''"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="预警值" prop="warningValue">
              <el-input v-model="form.warningValue" placeholder="请输入预警值"/>
            </el-form-item>
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" placeholder="请输入备注"/>
            </el-form-item>
            <!--        <el-form-item label="库存状态" prop="status">
                      <el-radio-group v-model="form.status">
                        <el-radio
                          v-for="dict in inventory_warning_status"
                          :key="dict.value"
                          :label="parseInt(dict.value)"
                        >{{dict.label}}</el-radio>
                      </el-radio-group>
                    </el-form-item>-->
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </el-col>
    </el-row>
  </div>

</template>

<script setup name="Warning">
import {listWarning, getWarning, delWarning, addWarning, updateWarning} from "@/api/inventory/warning";
import {listStorehouse} from "@/api/inventory/storehouse.js";
import {listInventory} from "@/api/inventory/inventory.js";

const {proxy} = getCurrentInstance();
const {inventory_warning_status} = proxy.useDict('inventory_warning_status');

const warningList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const treeLoading = ref(true)
let materialsList = reactive([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    warehouseId: null,
    warehouseName: null,
    materialId:null,
    materialName: null,
    warningValue: null,
    remarks: null,
    status: null,
    createdTime: null,
    updatedTime: null,
    quantity: null
  },
  rules: {
    /*materialName: [
      {required: true, message: "物料名称不能为空", trigger: "blur"}
    ],*/
    warningValue: [
      {required: true, message: "预警值不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "库存状态不能为空", trigger: "change"}
    ],
    createdTime: [
      {required: true, message: "创建时间不能为空", trigger: "blur"}
    ],
  }
});
const warehouse = reactive({
  id: 0,
  warehouseName: ''
})

const {queryParams, form, rules} = toRefs(data);

let data1 = ref([
  {
    id: 0,
    warehouseName: '全部仓库',
    children: []
  }
])
const defaultProps = {
  children: 'children',
  label: 'warehouseName'
}

function handleNodeClick(row) {
  warehouse.id = row.id
  if (row.id === 0) {
    queryParams.value.warehouseId = null
    warehouse.warehouseName = ''
    // getWarehouses()
  } else {
    queryParams.value.warehouseId = row.id
    warehouse.warehouseName = row.warehouseName
  }
  getList()
}

//获取预警行
function getRowClass({ row, rowIndex }) {
  if (row.quantity <= row.warningValue){
    return 'low-stock'
  }
}

//获取仓库集合
function getWarehouses() {
  treeLoading.value = true
  const query = {
    warehouseName:warehouse.warehouseName
  }
  listStorehouse(query).then(response => {
    data1.value[0].children = response.rows
    treeLoading.value = true
  })
}
getWarehouses()

//获取物料集合
function getMaterials(warehouseName){
  listInventory().then(response => {
    if (Array.isArray(response.rows)) {
      const filteredMaterials = response.rows
          .filter(item => {
            return item.materialsList && item.materialsList.length > 0 && item.warehouseName === warehouseName;
          }) // 只保留符合仓库ID和物料存在的条目
          .map(item => item.materialsList)  // 提取出每个条目的 materialsList
          .flat();  // 将嵌套的数组扁平化

      materialsList.splice(0, materialsList.length, ...filteredMaterials);
    }
  })
}

/** 查询库存预警列表 */
function getList() {
  loading.value = true; // 显示加载中
  listWarning(queryParams.value).then(response => {
    warningList.value = response.rows;
    total.value = response.total;
    getMaterials(warehouse.warehouseName)
    warningList.value.forEach(item => {
      if (item.quantity <= item.warningValue){
        item.status = 1;
      }else {
        item.status = 0
      }
    });
    loading.value = false; // 关闭加载中
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    warehouseName: null,
    materialName: null,
    warningValue: null,
    remarks: null,
    status: null,
    createdTime: null,
    updatedTime: null
  };
  proxy.resetForm("warningRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.warehouseName = warehouse.warehouseName
  form.value.warehouseId = warehouse.id
  open.value = true;
  title.value = "添加库存预警";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getWarning(_id).then(response => {
    form.value = response.data;
    form.value.warehouseName = warehouse.warehouseName
    open.value = true;
    title.value = "修改库存预警";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["warningRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateWarning(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addWarning(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除库存预警编号为"' + _ids + '"的数据项？').then(function () {
    return delWarning(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('inventory/warning/export', {
    ...queryParams.value
  }, `warning_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style scoped>
/* 修改选中节点字体颜色 */
::v-deep .el-tree .el-tree-node.is-current .el-tree-node__label {
  color: #409EFF;  /* 你可以设置为任何颜色 */
}

::v-deep .low-stock {
  background-color: #f8d7da;  /* 浅红色背景 */
  color: #721c24;             /* 深红色字体 */
  border: 1px solid #f5c6cb;  /* 边框颜色 */
}
</style>
